package com.wtsw.pulsosocial.view.menu;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout.LayoutParams;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wtsw.pulsosocial.R;
import com.wtsw.pulsosocial.controller.GestorEventos;
import com.wtsw.pulsosocial.controller.GestorUbicacion;
import com.wtsw.pulsosocial.model.list.EventAdapter;
import com.wtsw.pulsosocial.model.structure.Evento;
import com.wtsw.pulsosocial.view.event.FormEvento;
import com.wtsw.pulsosocial.view.event.ShowEvento;


public class EventosFragment extends Fragment  {
	private Button pulse;
	private ListView listEvents;		  
	private GoogleMap mMap;
	private LinearLayout map_Layout;
	private MODO_PANTALLA modo; //0=normal, 1=FullMapa
	private Button back;
	private android.view.ViewGroup.LayoutParams lista_events_layout;
	private ArrayAdapter<Evento> EventsAdapter;
	
	public enum MODO_PANTALLA {
	    LISTA_EVENTOS,
	    MAPA_EVENTOS
	}
	
    public static Fragment newInstance(Context context) {
        EventosFragment f = new EventosFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_eventos, container, false);
        modo = MODO_PANTALLA.LISTA_EVENTOS;
        listEvents = (ListView) rootView.findViewById(R.id.list_events);
        map_Layout = (LinearLayout) rootView.findViewById(R.id.mapLayout);
        lista_events_layout = map_Layout.getLayoutParams();
        creaEventsAdapter();
        
        listEvents.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {
				// TODO Auto-generated method stub
				Evento seleccionado = ((Evento)parent.getItemAtPosition(pos));
		        CameraPosition cameraPosition = new CameraPosition.Builder()
		        .target(seleccionado.getUbicacion())      // Sets the center of the map to Mountain View
		        .zoom(17)                   // Sets the zoom
		        .bearing(0)                // Sets the orientation of the camera to east
		        .tilt(45)                   // Sets the tilt of the camera to 30 degrees		        
		        .build();                   // Creates a CameraPosition from the builder  		        
		        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));		        
		        seleccionado.getMarker().showInfoWindow();
			}
        	
		});

        pulse = (Button) rootView.findViewById(R.id.pulse);
        pulse.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	startActivity(new Intent(getActivity(), FormEvento.class));    	        
            }
        });
        
       back = (Button) rootView.findViewById(R.id.back);
       back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	back.setVisibility(View.INVISIBLE);
            	modo=MODO_PANTALLA.LISTA_EVENTOS;
        		map_Layout.setLayoutParams(lista_events_layout);
        		CameraPosition cameraPosition = new CameraPosition.Builder()
        	       .target(GestorUbicacion.getLocation())      // Sets the center of the map to Mountain View
        	       .zoom(14)                   // Sets the zoom
        	       .bearing(0)                // Sets the orientation of the camera to east
        	       .tilt(45)                   // Sets the tilt of the camera to 30 degrees
        	       .build();                   // Creates a CameraPosition from the builder    
        	       mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });
        
        setUpMapIfNeeded();
        
        mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
        	private final View window = getActivity().getLayoutInflater().inflate(R.layout.custom_window, null);
			@Override
			public View getInfoWindow(com.google.android.gms.maps.model.Marker marker) {
				// TODO Auto-generated method stub
				//EventInfo eventInfo = eventMarkerMap.get(marker);
				Evento evento = GestorEventos.findByMarkerID(marker.getId());
				String title = evento.getNombre();			 
			             TextView txtTitle = ((TextView) window.findViewById(R.id.txtInfoWindowTitle));			 
			             if (title != null) {			 
			                 // Spannable string allows us to edit the formatting of the text.			 
			                 SpannableString titleText = new SpannableString(title);			
			                 marker.getId();
			                 titleText.setSpan(new ForegroundColorSpan(R.color.com_facebook_blue), 0, titleText.length(), 0);			 
			                 txtTitle.setText(titleText);			 
			             } else {			 
			                 txtTitle.setText("");
			 
			             }
			             ImageView imageCate = (ImageView) window.findViewById(R.id.ivInfoWindowMain);
			             Bitmap bitfile_cate = (evento.getSubCategoria().getIcono());                
			             imageCate.setImageBitmap(bitfile_cate);    			             			            
			    return window;
			}
			
			@Override
			public View getInfoContents(com.google.android.gms.maps.model.Marker marker) {
				// TODO Auto-generated method stub
				return null;
			}
		});
        
        mMap.setOnInfoWindowClickListener(
        		  new OnInfoWindowClickListener(){
        		    public void onInfoWindowClick(Marker marker){
        		    	Evento evento = GestorEventos.findByMarkerID(marker.getId());
        		    	Intent intent =new Intent(getActivity(), ShowEvento.class);
        		    	intent.putExtra("EventID",String.valueOf(evento.getId()));
        			    startActivity(intent);  
        		    }
        });
        
        mMap.setOnMapClickListener(new OnMapClickListener() {
			
			@Override
			public void onMapClick(LatLng ubicacion_tocada) {
				// TODO Auto-generated method stub			
				if (modo==MODO_PANTALLA.LISTA_EVENTOS) {
					modo=MODO_PANTALLA.MAPA_EVENTOS;
					back.setVisibility(View.VISIBLE);
				    map_Layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));	
				    CameraPosition cameraPosition = new CameraPosition.Builder()
			        //.target(ubicacion_tocada)      // Sets the center of the map to Mountain View
				    .target(GestorUbicacion.getLocation())
			        .zoom(17)                   // Sets the zoom
			        .bearing(0)                // Sets the orientation of the camera to east
			        .tilt(45)                   // Sets the tilt of the camera to 30 degrees		        
			        .build();                   // Creates a CameraPosition from the builder    
			        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
				}		       
			}
		});
        return rootView;
    }
    
    
    
	@Override
	public void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        creaEventsAdapter();        
        agregarPuntos();
    }	
	
	@Override
    public void onDestroyView() {
		super.onDestroyView();
        Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));  
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.remove(fragment);
        ft.commit();                
	}
    
    private void setUpMapIfNeeded() {
		 // Do a null check to confirm that we have not already instantiated the map.
       if (mMap == null) {
           // Try to obtain the map from the SupportMapFragment.
           mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
                   .getMap();
           // Check if we were successful in obtaining the map.            	            
           if (mMap != null)	
               setUpMap();
       }
	}

	private void setUpMap() {
       mMap.setMyLocationEnabled(true);          
       mMap.setMapType(1);       
       agregarPuntos();
       CameraPosition cameraPosition = new CameraPosition.Builder()
       .target(GestorUbicacion.getLocation())      // Sets the center of the map to Mountain View
       .zoom(14)                   // Sets the zoom
       .bearing(0)                // Sets the orientation of the camera to east
       .tilt(45)                   // Sets the tilt of the camera to 30 degrees
       .build();                   // Creates a CameraPosition from the builder    
       mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
   }
	
	private void agregarPuntos() {
		mMap.clear();
	       for (Evento evento:GestorEventos.getEventos()) {
	    	   	Marker marker = mMap.addMarker(new MarkerOptions()
	       		.position(evento.getUbicacion()).title(evento.getNombre())           
	       		.icon(BitmapDescriptorFactory.defaultMarker(evento.getStateColor())));
	    	   	evento.setMarker(marker);
	       }
	}
	
	private void creaEventsAdapter() {                     
		EventsAdapter = new EventAdapter(getActivity());
        listEvents.setAdapter(EventsAdapter);
	}

}
